<template>
  <div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="openDialog" >新增</el-button>
        <el-popover v-model="deleteVisible" :disabled="!multipleSelection.length" placement="top" width="160" >
          <p>确定要删除吗？</p>
          <div style="text-align: right; margin-top: 8px;">
            <el-button type="primary" link @click="deleteVisible = false" >取消</el-button>
            <el-button type="primary" @click="onDelete" >确定</el-button>
          </div>
          <template #reference>
            <el-button icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="deleteVisible = true" >删除</el-button>
          </template>
        </el-popover>
      </div>
      <el-table ref="multipleTable" style="width: 100%" tooltip-effect="dark" :data="tableData" row-key="ID" @selection-change="handleSelectionChange" >
        <!-- <el-table-column label="id" prop="id" width="120" /> -->
        <el-table-column type="selection" width="55" />
        <el-table-column align="left" label="名称" min-width="220" prop="name" />
        <el-table-column align="left" label="操作" >
          <template #default="scope">
        <el-button type="primary" link icon="edit" class="table-button" @click="updateEfficacyFunc(scope.row)" >变更</el-button>
            <el-button type="primary" link icon="edit" class="table-button" @click="relevancy(scope.row)" >关联文章</el-button>
            <el-button type="primary" link icon="delete" @click="deleteRow(scope.row)" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination layout="total, sizes, prev, pager, next, jumper" :current-page="page" :page-size="pageSize" :page-sizes="[10, 30, 50, 100]" :total="total" @current-change="handleCurrentChange" @size-change="handleSizeChange" />
      </div>
    </div>
    <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" :title="type==='create'?'添加':'修改'" destroy-on-close >
      <el-scrollbar height="500px">
        <el-form ref="elFormRef" :model="formData" label-position="right" :rules="rule" label-width="80px" >
          <el-form-item label="名称:" prop="name" >
            <el-input v-model="formData.name" :clearable="true" placeholder="请输入" />
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button
            type="primary"
            @click="enterDialog"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer v-model="drawer" direction="rtl" >
      <template #header>
        <div>
          <h4>关联文章</h4>
          <el-input v-model="filterText" placeholder="请输入搜索内容" clearable />
          <div class="flex gap-2 mt-2">
            
              <el-tree-select
                v-model="formData.category"
                :data="category"
                check-strictly
                :render-after-expand="false"
                :props="{
                value:'ID',
                label:'name',
              }"
               @change="GetArticleList"
              />
          </div>
        </div>

      </template>
      <template #default>
        <div>
          <el-tabs v-model="tag" @tab-change="GetArticleList">
            <el-tab-pane label="文本" name="richText">
              <el-tree ref="treeRefText" node-key="ID" :data="texts" :filter-node-method="filterTree" :props="{ label: 'title' }" show-checkbox @check-change="PushId" />
            </el-tab-pane>
            <el-tab-pane label="音频" name="audio">
              <el-tree ref="treeRefAudio" node-key="ID" :data="audios" :filter-node-method="filterTree" :props="{ label: 'title' }" show-checkbox @check-change="PushId" />
            </el-tab-pane>
            <el-tab-pane label="视频" name="video">
              <el-tree ref="treeRefVideo" node-key="ID" :data="videos" :filter-node-method="filterTree" :props="{ label: 'title' }" show-checkbox @check-change="PushId" />
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取消</el-button>
          <el-button
            type="primary"
            @click="confirmClick"
          >确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script>
export default {
  name: 'Efficacy'
}
</script>

<script setup>
import {
  createEfficacy,
  deleteEfficacy,
  deleteEfficacyByIds,
  updateEfficacy,
  findEfficacy,
  getEfficacyListByWhere,
  setEfficacyArticle,
  getEfficacyArticle,
} from '@/api/intersection/efficacy'

// 全量引入格式化工具 请按需保留
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, watch, nextTick } from 'vue'
import { getArticleList } from '@/api/cms/article'
import {getCategoryList} from '@/api/cms/category.js'

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  name: '',
  category: undefined,
})

// 验证规则
const rule = reactive({
})

const treeRefText = ref(null)
const treeRefAudio = ref(null)
const treeRefVideo = ref(null)

const filterText = ref('')

const active = ref({})

const drawer = ref(false)
const IDList=ref([])
const texts = ref([])
const audios = ref([])
const videos = ref([])

const filterTree = (_, tree) => {
  if (!filterText.value) return true
  return tree.title?.includes(filterText.value)
}

const category = ref([])

const getCategory = async () => {
  const res =  await getCategoryList({ page: 1, pageSize: 1000 })
  if (res.code === 0) {
    category.value = res.data
  }
}
getCategory()

const tag = ref('richText')
const GetArticleList= async () =>{
  const res = await getArticleList({ page: 1, pageSize: 1000, category: formData.value.category, type: tag.value })
  if (res.code === 0) {
    if (tag.value == "richText") {
      texts.value = res.data.list
    }
    if (tag.value == "video") {
      videos.value = res.data.list
    }
    if (tag.value == "audio") {
      audios.value = res.data.list
    }
    await nextTick()
    if (tag.value == "richText") {
      treeRefText.value?.setCheckedKeys(IDList.value)
    }
    if (tag.value == "video") {
      treeRefVideo.value?.setCheckedKeys(IDList.value)
    }
    if (tag.value == "audio") {
      treeRefAudio.value?.setCheckedKeys(IDList.value)
    }
  }
}
GetArticleList()
const PushId = (node, checked) => {
  if (checked) {
    if (!IDList.value.includes(node.ID)) {
      IDList.value.push(node.ID)
    }
  } else {
    const idx = IDList.value.indexOf(node.ID)
    if (idx !== -1) {
      IDList.value.splice(idx, 1)
    }
  }
}


const relevancy = async(row) => {
  active.value = row
  drawer.value = true
  const res = await getEfficacyArticle({ efficacyID: row.ID })
  if (res.code === 0) {
    const textIds = []
    const audioIds = []
    const videoIds = []
    res.data?.forEach(item => {
      if (item.type === 'richText') {
        textIds.push(Number(item.article_id))
      }
      if (item.type === 'audio') {
        audioIds.push(Number(item.article_id))
      }
      if (item.type === 'video') {
        videoIds.push(Number(item.article_id))
      }
    })
    IDList.value = Array.from(new Set([...textIds, ...audioIds, ...videoIds]))
    await GetArticleList()
  }
}
const confirmClick = async() => {

  const textIds = treeRefText.value.getCheckedKeys()
  const audioIds = treeRefAudio.value.getCheckedKeys()
  const videoIds = treeRefVideo.value.getCheckedKeys()

  const res = await setEfficacyArticle({
    efficacyID: active.value.ID,
    richText_id: textIds,
    audio_id: audioIds,
    video_id: videoIds,
  })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '关联成功'
    })
    drawer.value = false
  }
}

const cancelClick = () => {

}  

const elFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

//

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async() => {
  const table = await getEfficacyListByWhere({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteEfficacyFunc(row)
  })
}

// 批量删除控制标记
const deleteVisible = ref(false)

// 多选删除
const onDelete = async() => {
  const ids = []
  if (multipleSelection.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据'
    })
    return
  }
  multipleSelection.value &&
        multipleSelection.value.map(item => {
          ids.push(item.id)
        })
  const res = await deleteEfficacyByIds({ ids })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === ids.length && page.value > 1) {
      page.value--
    }
    deleteVisible.value = false
    getTableData()
  }
}

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateEfficacyFunc = async(row) => {
  const res = await findEfficacy({ id: row.id })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data
    dialogFormVisible.value = true
  }
}

// 删除行
const deleteEfficacyFunc = async(row) => {
  const res = await deleteEfficacy({ id: row.id })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
  }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)

// 打开弹窗
const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    name: '',
  }
}
// 弹窗确定
const enterDialog = async() => {
  elFormRef.value?.validate(async(valid) => {
    if (!valid) return
    let res
    switch (type.value) {
      case 'create':
        res = await createEfficacy(formData.value)
        break
      case 'update':
        res = await updateEfficacy(formData.value)
        break
      default:
        res = await createEfficacy(formData.value)
        break
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      getTableData()
    }
  })
}

watch(()=>[filterText.value],()=>{
  treeRefText.value?.filter()
  treeRefAudio.value?.filter()
  treeRefVideo.value?.filter()
})

</script>

<style>
.el-drawer__header{
  margin-bottom: 0;
}
</style>
